<?php

namespace V1;
class Message extends \ResourceClass
{
    public $isActive = true;
    public $remark = '消息接口';

    public function post(array $req, array $post, &$result)
    {
        if (!isset($req['uid'])){
            return 'require UID';
        }
        $touser = $req['from_user'];
        $date_stamp = date('Y-m-d H:i:s');
        $content = "新订单通知"
            .$date_stamp.
            "收到一笔新的订单支付".
            "商品明细：".$req['商品明细'].
            "下单时间：".$req['下单时间'].
            "配送地址：".$req['配送地址'].
            "联系人：".$req['联系人'].
            "付款状态：".$req['付款状态']
            ;
        $this->reply($touser,$content);
    }
    /**
     * @param $touser
     * @param $content
     * @return mixed
     */
    private function reply($touser,$content)
    {
        $app_id = "wxc71c53bfc2181690";
        $app_secret = "7e422b5c484583538afa95d4b6a8e544";
        $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_id.'&secret='.$app_secret);
        $res = json_decode($res, true);
        $token = $res['access_token'];
        $data = '{
            "touser":"'.$touser.'",
            "msgtype":"text",
            "text":
                {
                 "content":"'.$content.'"
                }
            }';
        $url = sprintf("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s", $token);
        $result = $this->https_post($url,$data);
        $final = json_decode($result);
        return $final;
    }

    /**
     * @param $url
     * @param $data
     * @return mixed|string
     */
    public function https_post($url,$data)
    {
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);//需要获取的URL地址
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);//禁用后cURL将终止从服务端进行验证
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);//检查服务器SSL证书中是否存在一个公用名(common name)
        curl_setopt($curl,CURLOPT_POST,1);//启用时会发送一个常规的POST请求
        curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//	全部数据使用HTTP协议中的"POST"操作来发送
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。 returntransfer
        $result = curl_exec($curl);
        if (curl_errno($curl))
        {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }
}